const path = require('path')
const fs = require('fs')
import { localConfig } from './storage'
import { app } from 'electron'

//========读取本地配置工具类========
//========读取本地配置工具类========
//========读取本地配置工具类========
export class FileUtils {
  defaultConfig = { name: '项目管理', projectPathStr: '' }
  configPathDev = 'doc/appCacheDev/localConfig.json'
  configPathProdMac = 'appCache/localConfig.json'
  configPathProdWin = 'resources/appCache/localConfig.json'
  configFilePath = ''
  initFileConfig = false

  constructor() {
    console.log('FileUtils-constructor2')
    this.configFilePath = this._initPath()
    this.initFileConfig = this._initConfig()
  }

  //初始化配置文件路径
  _initPath() {
    console.log('_initPath', process.cwd())
    console.log('_initPath', app.getAppPath())
    const isBuild = app.isPackaged
    //1.应用程序所在的根目录
    let appDirectory =
      process.platform === 'darwin' && isBuild
        ? app.getAppPath().substring(0, app.getAppPath().lastIndexOf('/'))
        : process.cwd()
    //2.正式打包后的配置文件路径
    let configPathProd =
      process.platform === 'darwin' ? this.configPathProdMac : this.configPathProdWin
    let config_path_env = isBuild ? configPathProd : this.configPathDev
    return path.resolve(appDirectory, ...config_path_env.split('/'))
  }

  //初始化config
  _initConfig() {
    try {
      const config = this.readConfig()
      console.log('_initConfig', this.configFilePath)
      console.log('_initConfig', localConfig.config)
      console.log('_initConfig', config)
      if (config) return true
      console.log('_initConfig', 111)
      console.log('_initConfig', this.defaultConfig)
      const content = JSON.stringify(this.defaultConfig)
      console.log('_initConfig', content)
      fs.writeFileSync(this.configFilePath, content)
      console.log('_initConfig---')
      console.log('_initConfig===', localConfig.config)
      localConfig.config = this.defaultConfig
      console.log('_initConfig===', localConfig.config)
      return true
    } catch (e) {
      return false
    }
  }

  //读取文件
  readConfig() {
    try {
      const result = fs.readFileSync(this.configFilePath)
      localConfig.config = JSON.parse(result as String)
      return result
    } catch (error) {
      return false
    }
  }

  //写入文件
  writeConfig(value) {
    try {
      const content = JSON.stringify(value)
      fs.writeFileSync(this.configFilePath, content)
      return true
    } catch (e) {
      return false
    }
  }
}
